package com.example.mallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.dto.BoundsDTO;
import com.dto.SkuFullReductionDTO;
import com.example.mallproduct.controller.vo.Attr;
import com.example.mallproduct.controller.vo.BaseAttrs;
import com.example.mallproduct.controller.vo.Bounds;
import com.example.mallproduct.controller.vo.Images;
import com.example.mallproduct.controller.vo.SkuInfoVO;
import com.example.mallproduct.controller.vo.SkuItemSaleAttrVo;
import com.example.mallproduct.controller.vo.Skus;
import com.example.mallproduct.controller.vo.SpuItemGroupAttrVo;
import com.example.mallproduct.controller.vo.SpuItemVO;
import com.example.mallproduct.dao.AttrGroupDao;
import com.example.mallproduct.dao.SkuInfoDao;
import com.example.mallproduct.entity.AttrEntity;
import com.example.mallproduct.entity.ProductAttrValueEntity;
import com.example.mallproduct.entity.SkuImagesEntity;
import com.example.mallproduct.entity.SkuInfoEntity;
import com.example.mallproduct.entity.SkuSaleAttrValueEntity;
import com.example.mallproduct.entity.SpuImagesEntity;
import com.example.mallproduct.entity.SpuInfoDescEntity;
import com.example.mallproduct.entity.SpuInfoEntity;
import com.example.mallproduct.fegin.CouponFeginService;
import com.example.mallproduct.service.AttrService;
import com.example.mallproduct.service.ProductAttrValueService;
import com.example.mallproduct.service.SkuImagesService;
import com.example.mallproduct.service.SkuInfoService;
import com.example.mallproduct.service.SkuSaleAttrValueService;
import com.example.mallproduct.service.SpuImagesService;
import com.example.mallproduct.service.SpuInfoDescService;
import com.example.mallproduct.service.SpuInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeginService couponFeginService;

    @Autowired
    private SkuInfoDao skuInfoDao;
    @Autowired
    private AttrGroupDao attrGroupDao;

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10,
            10, TimeUnit.SECONDS, new LinkedBlockingQueue(100),
            Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    /**
     * 发布商品保存数据
     *
     * @param skuInfoVO
     */
    @Transactional
    @Override
    public void saveDetails(SkuInfoVO skuInfoVO) {
//        保存spu基础信息 pms-spu-info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(skuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoService.save(spuInfoEntity);
//        保存spu详细信息 pms-spu-info-desc
        List<String> decriptList = skuInfoVO.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decriptList));
        spuInfoDescService.save(descEntity);
//        保存图集信息 pms-spu-images
        List<String> imageList = skuInfoVO.getImages();
        List<SpuImagesEntity> spuImagesEntityList = imageList.stream().map(item -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(item);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntityList);
//        保存规格参数 pms-product-attr-value
        List<BaseAttrs> baseAttrsList = skuInfoVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrsList.stream().map(arrt -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(arrt.getAttrId());
            productAttrValueEntity.setAttrValue(arrt.getAttrValues());
            AttrEntity attrEntity = attrService.getById(arrt.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(attrEntity.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);
//        保存当前的spu对应的所有sku
//                保存sku信息 pms-sku-info

        List<Skus> skuList = skuInfoVO.getSkus();
        if (!CollectionUtils.isEmpty(skuList)) {
            skuList.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> imagesList = item.getImages();
                String defaultImg = "";
                for (Images images : imagesList) {
                    if (images.getDefaultImg() == 1) {
                        defaultImg = images.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
//                保存sku图片 pms-sku-image
                List<SkuImagesEntity> skuImagesEntityList = imagesList.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                //保存满减信息，折扣，会员价 mall-sms：sms-sku-ladder，sms-full-reduction，sms-member-price
                SkuFullReductionDTO skuFullReductionDTO = new SkuFullReductionDTO();
                BeanUtils.copyProperties(item, skuFullReductionDTO);
                skuFullReductionDTO.setSkuId(skuInfoEntity.getSkuId());
                couponFeginService.saveFullSkuReduction(skuFullReductionDTO);

                // sku的销售属性信息 pms-sku-sale-attr-value
                List<Attr> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(sale -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
            });

        }

        //保存spu的积分信息 mall-sms：sms-spu-bounds
        Bounds bounds = skuInfoVO.getBounds();
        BoundsDTO boundsDTO = new BoundsDTO();
        BeanUtils.copyProperties(bounds, boundsDTO);
        boundsDTO.setSpuId(spuInfoEntity.getId());

        couponFeginService.saveBound(boundsDTO);

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        // 检索关键字
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        // 分类
        String catalogId = (String) params.get("catalogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }
        // 品牌
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        // 价格区间
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                // 如果max=0那么我们也不需要加这个条件
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) == 1) {
                    // 说明 max > 0
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据spuId查询sku信息
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> skuInfoBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * 查询商品详细
     *
     * @param skuId
     * @return
     */
    @Override
    public SpuItemVO skuDetails(Long skuId) throws ExecutionException, InterruptedException {

        SpuItemVO vo = new SpuItemVO();
        CompletableFuture<SkuInfoEntity> skuInfoEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {
            // 1.sku的基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = getById(skuId);
            vo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> voidCompletableFuture = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            // 3.获取spu中的销售属性的组合
            List<SkuItemSaleAttrVo> saleAttrs = skuInfoDao.getSkuSaleAttrValueBySpuId(res.getSpuId());
            vo.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        CompletableFuture<Void> voidCompletableFuture1 = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            // 4.获取SPU的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            vo.setDesc(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> voidCompletableFuture2 = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            // 5.获取SPU的规格参数
            List<SpuItemGroupAttrVo> groupAttrVo = attrGroupDao.getAttrgroupWithSpuId(res.getSpuId(), res.getCatalogId());
            vo.setBaseAttrs(groupAttrVo);
        }, threadPoolExecutor);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            // 2.sku的图片信息pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.list((Wrapper<SkuImagesEntity>) new QueryWrapper().eq("sku_id", skuId));
            vo.setImages(images);
        }, threadPoolExecutor);

        CompletableFuture.allOf(skuInfoEntityCompletableFuture,voidCompletableFuture,voidCompletableFuture1,voidCompletableFuture2,skuImagesFuture).get();

        return vo;
    }

    @Override
    public List<String> getSaleAttrs(Long skuId) {
        return skuInfoDao.getSaleAttrs(skuId);
    }
}


